<template>
    <el-main>
      <!-- 顶部操作区 -->
      <el-form :inline="true">
        <el-form-item label="客户姓名">
          <el-input v-model="filters.clientName" placeholder="请输入客户姓名" clearable @keyup.enter="onSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="success" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        <el-table-column type="index" label="序号" width = "80" />
        <el-table-column prop="clientName" label="客户姓名" />
        <el-table-column prop="checkOutType" label="退住类型" />
        <el-table-column prop="checkOutReason" label="退住原因" show-overflow-tooltip />
        <el-table-column prop="checkOutTime" label="退住时间" :formatter="formatDateTime" />
        <el-table-column prop="checkOutReviewStatus" label="审核状态">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.checkOutReviewStatus)">
              {{ scope.row.checkOutReviewStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkOutReviewTime" label="审核时间" :formatter="formatDateTime" />
        <el-table-column v-if="userRole === '管理员'" label="操作" >
          <template #default="scope">
            <el-button
                type="warning"
                @click="openAuditDialog(scope.row)"
                :disabled="scope.row.checkOutReviewStatus !== '已提交'"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[6, 10, 20, 50]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
      </div>

      <!-- 审核对话框 (系统管理员使用) -->
      <el-dialog v-model="auditDialog.visible" title="退住申请审核" width="500px">
        <el-form ref="auditFormRef" :model="auditForm.data" :rules="auditForm.rules" label-width="100px">
          <el-form-item label="审核结果" prop="checkOutReviewStatus">
            <el-radio-group v-model="auditForm.data.checkOutReviewStatus">
              <el-radio :value="'通过'">通过</el-radio>
              <el-radio :value="'不通过'">不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见" prop="checkOutDescription">
            <el-input v-model="auditForm.data.checkOutDescription" type="textarea" :rows="3" placeholder="若不通过，请填写原因" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="auditDialog.visible=false">取消</el-button>
          <el-button type="primary" @click="submitAudit" :loading="auditDialog.loading">确认审核</el-button>
        </template>
      </el-dialog>
    </el-main>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listCheckOutRequests, applyForCheckOut, auditRequest } from '@/api/apiList/checkOut.js';

const userRole = ref(localStorage.getItem('role'));
const userId = ref(localStorage.getItem('adminId'));
const numericUserId = userId.value ? parseInt(userId.value, 10) : null;

// --- 通用状态 ---
const loading = ref(false);
const tableData = ref([]);
const filters = reactive({ clientName: '' });
const pagination = reactive({ total: 0, currentPage: 1, pageSize: 6 });

// --- 审核表单状态 ---
const auditDialog = reactive({ visible: false, loading: false });
const auditFormRef = ref(null);
const currentRecordId = ref(null);
const getInitialAuditForm = () => ({ checkOutReviewStatus: '通过', checkOutDescription: '同意。' });
const auditForm = reactive({
  data: getInitialAuditForm(),
  rules: {
    checkOutReviewStatus: [{ required: true, message: '请选择审核结果' }],
  }
});

// --- 方法 ---
async function fetchData() {
  loading.value = true;
  console.log(userRole.value,userId.value);
  try {
    const query = { clientName: filters.clientName };
    if (userRole.value === '健康管家') {
      query.adId = numericUserId;
    }
    const params = { pageNum: pagination.currentPage, pageSize: pagination.pageSize, query };
    const pageData = await listCheckOutRequests(params);
    tableData.value = pageData.records;
    pagination.total = pageData.total;
  } catch (error) { console.error("获取列表失败:", error); }
  finally { loading.value = false; }
}
function handlePageChange(newPage) {
  pagination.currentPage = newPage;
  fetchData();
}

function handleSizeChange(newSize) {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  fetchData();
}

const getStatusTag = (s) => {
  const tagMap = {
    '已提交': 'primary',
    '通过': 'success',
    '不通过': 'danger'
  };
  return tagMap[s] || 'info'; // 如果状态未知，返回灰色标签
};
const onSearch = () => { pagination.currentPage = 1; fetchData(); };
const onReset = () => {filters.clientName = ''; onSearch();};

const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) {
    return '';
  }
  try {
    const date = new Date(cellValue);
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '无效日期';
    }
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    return '格式化错误';
  }
};

function openAuditDialog(row) {
  currentRecordId.value = row.checkOutId;
  Object.assign(auditForm.data, getInitialAuditForm());
  if (auditFormRef.value) auditFormRef.value.clearValidate();
  auditDialog.visible = true;
}

function submitAudit() {
  if (!auditFormRef.value) return;
  auditFormRef.value.validate(async (valid) => {
    if(!valid) return;
    auditDialog.loading = true;
    try {
      const auditData = {
        checkOutId: currentRecordId.value,         // 必需：要更新哪条记录
        adId: numericUserId,                        // 必需：审核人是谁
        checkOutReviewStatus: auditForm.data.checkOutReviewStatus,
        checkOutDescription: auditForm.data.checkOutDescription
      };
      // 2. 调用API，传入组装好的对象
      await auditRequest(auditData);
      ElMessage.success('审核操作成功');
      auditDialog.visible = false;
      fetchData();
    } catch(e) {
      console.error("审核失败:", e);
    }
    finally {
      auditDialog.loading = false;
    }
  });
}


onMounted(
    fetchData
);

</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
